﻿
using AutoTestCommunication_Service.Class;
using Google.Protobuf.WellKnownTypes;
using Microsoft.Win32;
using MySql.Data.MySqlClient;
using MySqlX.XDevAPI.Relational;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Ocsp;
using Org.BouncyCastle.Utilities.Collections;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;

namespace AutoTestCommunication_Service
{
    class Public
    {
        public class EquipmentList

        {
            public int Local_ID { get; set; }
            public string Local_EquipmentNumber { get; set; }
            public string Local_EquipmentType { get; set; }
            public string Local_EquipmentName1 { get; set; }
            public string Local_EquipmentName2 { get; set; }
            public string Local_EquipmentArea { get; set; }
            public bool Local_IsEnabled { get; set; }
            public int EquipmentStatus { get; set; }
            public int RunningTime { get; set; }

            //PUBLIC
            public int PreStatus;

            public int TurnOn;

        }
        public class EquipmentParameters
        {
            public string Client_IP { get; set; }

            public string PN { get; set; }

            public string 电源型号 { get; set; }
            public string TreeName { get; set; }
            public List<REQclass> REQList { get; set; }

            public bool REQstate { get; set; }

            public int REQsequence { get; set; }
            public string PDST { get; set; }
            public string Last_POLO { get; set; }
            public string[] WDPCD { get; set; }
            public ConcurrentDictionary<int, Parameter> CDSDT { get; set; }
            public  List<double>  Io { get; set; }
            public  List<double>  Ith { get; set; }
            public  List<double>  Po { get; set; }
            
            public bool MysqlCanUpdate { get; set; }

            public double K0 { get; set; }
            public double Y0 { get; set; }
            public string I3000 { get; set; }
            public string I2800 { get; set; }
            public string 电流百分比3000 { get; set; }
            public string 电流百分比2800 { get; set; }
            public List<string> EPListPOLOClass { get; set; }
            public string PCBSN { get; set; }
            public string GGXL { get; set; }
        }
        public class BindingLB : INotifyPropertyChanged
        {
            Brush _LBForeground;
            public Brush LBForeground
            {
                get
                {
                    return _LBForeground;
                }
                set
                {
                    _LBForeground = value;
                    NotifyPropertyChanged(nameof(LBForeground));
                }
            }

            string _LBContent;
            public string LBContent
            {
                get
                {
                    return _LBContent;
                }
                set
                {
                    _LBContent = value;
                    NotifyPropertyChanged(nameof(LBContent));
                }
            }

            bool _Startlisten;
            public bool Startlisten
            {
                get
                {
                    return _Startlisten;
                }
                set
                {
                    _Startlisten = value;
                    NotifyPropertyChanged(nameof(Startlisten));
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
        public class REQclass
        {
            public string StrName { get; set; }

            public string Strvalue { get; set; }


        }
        public class Tablestructureclass
        {
            public int ID { get; set; }

            public string NameC { get; set; }

            public string NameE { get; set; }

            public int CANREAD { get; set; }

            public string POLO { get; set; }

            public string value { get; set; }

            public int judge { get; set; }
        }
        public class Parameter : INotifyPropertyChanged

        {

            int _Local_ID;
            public int Local_ID
            {
                get
                {
                    return _Local_ID;
                }
                set
                {
                    _Local_ID = value;
                    NotifyPropertyChanged(nameof(Local_ID));
                }
            }

            string _Local_NameE;
            public string Local_NameE
            {
                get
                {
                    return _Local_NameE;
                }
                set
                {
                    _Local_NameE = value;
                    NotifyPropertyChanged(nameof(Local_NameE));
                }
            }

            string _Local_NameC;
            public string Local_NameC
            {
                get
                {
                    return _Local_NameC;
                }
                set
                {
                    _Local_NameC = value;
                    NotifyPropertyChanged(nameof(Local_NameC));
                }
            }

            string _Local_CommandName;
            public string Local_CommandName
            {
                get
                {
                    return _Local_CommandName;
                }
                set
                {
                    _Local_CommandName = value;
                    NotifyPropertyChanged(nameof(Local_CommandName));
                }
            }

            int _Local_CMDID;
            public int Local_CMDID
            {
                get
                {
                    return _Local_CMDID;
                }
                set
                {
                    _Local_CMDID = value;
                    NotifyPropertyChanged(nameof(Local_CMDID));
                }
            }

            string _Local_POLO;
            public string Local_POLO
            {
                get
                {
                    return _Local_POLO;
                }
                set
                {
                    _Local_POLO = value;
                    NotifyPropertyChanged(nameof(Local_POLO));
                }
            }

            int _Local_Ratio;
            public int Local_Ratio
            {
                get
                {
                    return _Local_Ratio;
                }
                set
                {
                    _Local_Ratio = value;
                    NotifyPropertyChanged(nameof(Local_Ratio));
                }
            }

            string _Local_DataSource;
            public string Local_DataSource
            {
                get
                {
                    return Local_DataSource;
                }
                set
                {
                    _Local_DataSource = value;
                    NotifyPropertyChanged(nameof(Local_DataSource));
                }
            }

            int _Local_NeedUpload;
            public int Local_NeedUpload
            {
                get
                {
                    return _Local_NeedUpload;
                }
                set
                {
                    _Local_NeedUpload = value;
                    NotifyPropertyChanged(nameof(Local_NeedUpload));
                }
            }

            int _Local_IsUpload;
            public int Local_IsUpload
            {
                get
                {
                    return _Local_IsUpload;
                }
                set
                {
                    _Local_IsUpload = value;
                    NotifyPropertyChanged(nameof(Local_IsUpload));
                }
            }
            int _Local_IsEnable;
            public int Local_IsEnable
            {
                get
                {
                    return _Local_IsEnable;
                }
                set
                {
                    _Local_IsEnable = value;
                    NotifyPropertyChanged(nameof(Local_IsEnable));
                }
            }
            double _doublevalue;
            public double Doublevalue
            {
                get
                {
                    return _doublevalue;
                }
                set
                {
                    _doublevalue = value;
                    NotifyPropertyChanged(nameof(Doublevalue));
                }
            }
            string _stringvalue;
            public string Stringvalue
            {
                get
                {
                    return _stringvalue;
                }
                set
                {
                    _stringvalue = value;
                    NotifyPropertyChanged(nameof(Stringvalue));
                }
            }

            Brush _Background;
            public Brush Background
            {
                get
                {
                    return _Background;
                }
                set
                {
                    _Background = value;
                    NotifyPropertyChanged(nameof(Background));
                }
            }

            string _strBackground;
            public string StrBackground
            {
                get
                {
                    return _strBackground;
                }
                set
                {
                    _strBackground = value;
                    NotifyPropertyChanged(nameof(StrBackground));
                }
            }
            bool _HasSend;
            public bool HasSend
            {
                get
                {
                    return _HasSend;
                }
                set
                {
                    _HasSend = value;
                    NotifyPropertyChanged(nameof(HasSend));
                }
            }
            int _Row;
            public int Row
            {
                get
                {
                    return _Row;
                }
                set
                {
                    _Row = value;
                    NotifyPropertyChanged(nameof(Row));
                }
            }

            int _Column;
            public int Column
            {
                get
                {
                    return _Column;
                }
                set
                {
                    _Column = value;
                    NotifyPropertyChanged(nameof(Column));
                }
            }

            int _ColumnSpan;
            public int ColumnSpan
            {
                get
                {
                    return _ColumnSpan;
                }
                set
                {
                    _ColumnSpan = value;
                    NotifyPropertyChanged(nameof(ColumnSpan));
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
        public class IRAYArea
        {
            public int startX { get; set; }
            public int startY { get; set; }

            public int endX { get; set; }
            public int endY { get; set; }
        }
        public class IRAY
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Describe { get; set; }
            public ConcurrentDictionary<int, IRAYArea> CDIRAYArea { get; set; }

        }


        public static ConcurrentDictionary<string, List<string>> REQList = new ConcurrentDictionary<string, List<string>>();
        public static string Apppath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; //获取启动了应用程序的可执行文件的路径，不包括可执行文件的名称
        public static IWorkbook SDTIBook = null;
        public static DataTable SDT = new DataTable();
        public static IWorkbook SDT1IBook = null;
        public static DataTable SDT1 = new DataTable();
        public static IWorkbook SDT2IBook = null;
        public static DataTable SDT2 = new DataTable();
        public static IWorkbook WCONIBook = null;
        public static DataTable WCON = new DataTable();
        public static byte[] head = new byte[8];
        public static ConcurrentDictionary<string, string> PCB = new ConcurrentDictionary<string, string>();
        public static ConcurrentDictionary<string, string> PowerLetter = new ConcurrentDictionary<string, string>();
        public static ConcurrentDictionary<string, string> RLPCD = new ConcurrentDictionary<string, string>();
        public static List<string> strreq = new List<string>();
        //=====================测试计时======================
        public static double 时间差;
        public static long start_Value = 0;
        public static long freq = 0;
        public static long stop_Value = 0;
        //=====================SQL===========================
        public static ConcurrentDictionary<int, Tablestructureclass> resuilt1structure = new ConcurrentDictionary<int, Tablestructureclass>();
        public static ConcurrentDictionary<int, Tablestructureclass> resuilt2structure = new ConcurrentDictionary<int, Tablestructureclass>();

        public static ConcurrentDictionary<int, Tablestructureclass> luminescenceclassification3000 = new ConcurrentDictionary<int, Tablestructureclass>();
        public static ConcurrentDictionary<string, int> CD001文件号 = new ConcurrentDictionary<string, int>();
        public static ConcurrentDictionary<string, IRAY> CDIRAYClass = new ConcurrentDictionary<string, IRAY>();
        //0-100%测试
        public static List<string> ListCommandName = new List<string>() { "ST10", "ST9", "ST12", "ST20", "ST21", "ST11", "ST22", "ST23", "ST24", "ST13", "ST19" };
        public static List<string> ListPOLOClass = new List<string>()   { "5%"  , "10%", "50%" , "70%" , "75%" , "80%" , "85%" , "90%" , "95%" , "100%", "101%" };

        public static BindingLB BDHostHoststate = new BindingLB();
        public static BindingLB BDopticalfiberstate = new BindingLB();
        public static BindingLB BDPumpsourcestate = new BindingLB();
        public static BindingLB BDjiandaoyunstate = new BindingLB();
        public static BindingLB BDmessage = new BindingLB();

        public static BindingLB BDstarttime = new BindingLB();
        public static BindingLB BDendtime = new BindingLB();
        public static BindingLB BDcosttime = new BindingLB();
        public static ConcurrentDictionary<string, Public.EquipmentParameters> EP = new ConcurrentDictionary<string, Public.EquipmentParameters>();
        [DllImport("kernel32")]
        public static extern int QueryPerformanceFrequency(ref long x);
        [DllImport("kernel32")]
        public static extern int QueryPerformanceCounter(ref long x);
        public static string RemoveNumber(string key)
        {
            return System.Text.RegularExpressions.Regex.Replace(key, @"\d", "");
        }

        /// <summary>
        /// 去掉字符串中的非数字
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string RemoveNotNumber(string key)
        {
            return System.Text.RegularExpressions.Regex.Replace(key, @"[^\d]*", "");
        }
        public static void AddNew3000EP(string IP)
        {
            try
            {
                if (Public.EP.ContainsKey(IP))
                {
                    return;
                }
                else
                {
                    ConcurrentDictionary<int, Parameter> NewList = new ConcurrentDictionary<int, Parameter>();
                    DataRow[] myDataRow1 = SDT1.Select(); DataRow[] myDataRow2 = SDT2.Select();
                    for (int i = 0; i < myDataRow1.Count(); i++)
                    {                       
                        try
                        {
                            if (myDataRow1[i]["ID"]!=null)
                            {
                                Parameter P = new Parameter()
                                {
                                    Local_ID = Convert.ToInt32(myDataRow1[i]["ID"]),
                                    Local_NameE = Convert.ToString(myDataRow1[i]["NameE"]),
                                    Local_NameC = Convert.ToString(myDataRow1[i]["NameC"]),
                                    Local_CommandName = Convert.ToString(myDataRow1[i]["CommandName"]),
                                    Local_CMDID = Convert.ToInt32(myDataRow1[i]["CMDID"]),
                                    Local_Ratio = Convert.ToInt32(myDataRow1[i]["Ratio"]),
                                    Local_DataSource = Convert.ToString(myDataRow1[i]["DataSource"]),
                                    Local_NeedUpload = Convert.ToInt32(myDataRow1[i]["NeedUpload"]),
                                    Local_IsUpload = Convert.ToInt32(myDataRow1[i]["IsUpload"]),
                                    Local_IsEnable = Convert.ToInt32(myDataRow1[i]["IsEnable"]),
                                    Doublevalue = 1,
                                    Background = new SolidColorBrush(Colors.Yellow),
                                    StrBackground = "Yellow",
                                    Stringvalue = "N/A",
                                    HasSend = false
                                };

                                NewList.TryAdd(i, P);
                            }
                            
                        }
                        catch(Exception ex)
                        {
                            TraceMethodInfo(ex.Message + ex.StackTrace);
                        }

                        
                    }

                    for (int i = 0; i < ListPOLOClass.Count; i++)
                    {
                        for (int j = 0; j < myDataRow2.Count(); j++)
                        {
                            Parameter P = new Parameter()
                            {

                                Local_ID = NewList.Count(),
                                Local_NameE = ListCommandName[i] + Convert.ToString(myDataRow2[j]["NameE"]),
                                Local_NameC = ListCommandName[i] + Convert.ToString(myDataRow2[j]["NameC"]),
                                Local_CommandName = ListCommandName[i],
                                Local_CMDID = Convert.ToInt32(myDataRow2[j]["CMDID"]),
                                Local_Ratio = Convert.ToInt32(myDataRow2[j]["Ratio"]),
                                Local_DataSource = Convert.ToString(myDataRow2[j]["DataSource"]),
                                Local_NeedUpload = Convert.ToInt32(myDataRow2[j]["NeedUpload"]),
                                Local_IsUpload = Convert.ToInt32(myDataRow2[j]["IsUpload"]),
                                Local_IsEnable = Convert.ToInt32(myDataRow2[j]["IsEnable"]),
                                Doublevalue = 1,
                                Background = new SolidColorBrush(Colors.Yellow),
                                StrBackground = "Yellow",
                                Stringvalue = "N/A",
                                HasSend = false
                            };

                            NewList.TryAdd(NewList.Count(), P);
                        }
                    }
                    SDT.Clear();
                    for (int i=0;i< NewList.Count();i++)
                    {
                        SDT.Rows.Add(NewList[i].Local_ID, NewList[i].Local_NameE, NewList[i].Local_NameC, NewList[i].Local_CommandName, NewList[i].Local_CMDID, NewList[i].Local_Ratio, 
                        NewList[i].Local_NeedUpload, NewList[i].Local_IsUpload, NewList[i].Local_IsEnable, NewList[i].Doublevalue, NewList[i].Background, NewList[i].StrBackground, NewList[i].Stringvalue, NewList[i].HasSend);
                    }
                    List<string> ListPOLO = new List<string>() { "5%", "10%", "50%", "70%", "75%", "80%", "85%", "90%", "95%", "100%", "101%" };

                    EquipmentParameters EquipmentParameters = new EquipmentParameters()
                    {
                        PN = "",
                        Client_IP = IP,
                        TreeName = "IP" + Public.RemoveNotNumber(IP),
                        CDSDT = NewList,
                        REQstate = false,
                        REQList = null,
                        MysqlCanUpdate = false,
                        PDST = "N/A",
                        WDPCD = null,
                        Last_POLO="",
                        Io = null,
                        Ith = null,
                        Po = null,
                        K0 = 0,
                        Y0 = 0,
                        I3000="0",
                        I2800="0",
                        电流百分比3000 = "",
                        电流百分比2800 = "",
                        EPListPOLOClass= ListPOLO
                    };
                   Public.EP.TryAdd(IP, EquipmentParameters);
                }
            }
            catch (Exception ex)
            {
                 TraceMethodInfo(ex.Message+ex.StackTrace);
            }

        }
        public static void BDParameter()
        {
            //try
            //{

            //    DataRow[] myDataRow1 = SDT.Select();
            //    for (int i = 0; i < myDataRow1.Count(); i++)
            //    {
            //        Parameter P = new Parameter()
            //        {
            //            Local_ID = Convert.ToInt32(myDataRow1[i]["ID"]),
            //            Local_NameE = Convert.ToString(myDataRow1[i]["NameE"]).Trim(),
            //            Local_NameC = Convert.ToString(myDataRow1[i]["NameC"]).Trim(),
            //            Local_CommandName = Convert.ToString(myDataRow1[i]["CommandName"]).Trim(),
            //            Row = Convert.ToInt32(myDataRow1[i]["Row"]),
            //            Column = Convert.ToInt32(myDataRow1[i]["Column"]),
            //            ColumnSpan = Convert.ToInt32(myDataRow1[i]["ColumnSpan"]),
            //            Background = new SolidColorBrush(Colors.Red),
            //            StrBackground = "Red",
            //            Stringvalue = "N/A"
            //        };
            //        DigitalService.BDlist.TryAdd(i, P);
            //    }
            //}
            //catch (Exception ex)
            //{
            //     TraceMethodInfo(ex.Message+ex.StackTrace);
            //}
        }
        public static bool CRCCheck(byte[] buffer)
        {
            int reCRC = CRC16H(buffer, 0, buffer.Length - 2);//公式法
            int crcHi1 = (Byte)(reCRC % 256);
            int crcLo1 = (Byte)(reCRC / 256);
            if (buffer.Length >= 2)
            {
                if ((crcHi1 == buffer[buffer.Length - 2]) & (crcLo1 == buffer[buffer.Length - 1]))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        public static ushort CRC16(byte[] bytes)
        {
            int crc = 0xffff;
            for (int n = 0; n < bytes.Length; n++)
            {
                byte i;
                crc = crc ^ bytes[n];
                for (i = 0; i < 8; i++)
                {
                    int TT;
                    TT = crc & 1;
                    crc = crc >> 1;
                    crc = crc & 0x7fff;
                    if (TT == 1)
                    {
                        crc = crc ^ 0xa001;
                    }
                    crc = crc & 0xffff;
                }
            }
            return (ushort)crc;
        }
        public static int CRC16H(byte[] Data, int start, int size)
        {
            byte CRC16Lo, CRC16Hi;       //CRC寄存器
            byte CL, CH;                   //多项式码&HA001
            byte SaveHi, SaveLo;
            int i, Flag;
            int CRC16_A;
            CRC16Lo = 0xFF;
            CRC16Hi = 0xFF;
            CL = 0x1;
            CH = 0xA0;
            for (i = 0; i <= size - 1; i++)
            {
                CRC16Lo = Convert.ToByte(CRC16Lo ^ Data[start + i]);         //每一个数据与CRC寄存器进行异或
                for (Flag = 0; Flag <= 7; Flag++)
                {
                    SaveHi = CRC16Hi;
                    SaveLo = CRC16Lo;
                    CRC16Hi = Convert.ToByte(CRC16Hi / 2);                 //高位右移一位
                    CRC16Lo = Convert.ToByte(CRC16Lo / 2);                 //低位右移一位

                    if ((SaveHi & 0x1) == 0x1)//如果高位字节最后一位为1
                    {
                        CRC16Lo = Convert.ToByte(CRC16Lo | 0x80);//则低位字节右移后前面补1

                    }
                    if ((SaveLo & 0x1) == 0x1)//如果LSB为1，则与多项式码进行异或
                    {
                        CRC16Hi = Convert.ToByte(CRC16Hi ^ CH);
                        CRC16Lo = Convert.ToByte(CRC16Lo ^ CL);
                    }
                }
            }

            CRC16_A = CRC16Hi;           //CRC高位
            CRC16_A = CRC16_A * 256;
            CRC16_A = CRC16_A + CRC16Lo;          //CRC低位
            return CRC16_A;
        }
        public static string FindREQName(string PN, string IP, string PCBN)
        {
            string REQName = "";
            if (PCB.ContainsKey(PCBN))
            {
                REQName = PCB[PCBN].ToString();
            }

            return REQName;
        }
        public static List<REQclass> ReadREQtxt(string REQtxtName,string PowerPN,bool Is235,string power,string pn)
        {
            List<REQclass> strREQ = new List<REQclass>();
            try
            {
                //if (pn == "BFL-CW1500-A" || pn == "BFL-CW1500-A-N" || pn == "BFL-CW2000-B" || pn == "BFL-CW2000-B-N")
                //{
                //    if (REQtxtName == "P405")
                //    {
                //        REQtxtName = "P405JS";
                //    }
                //    else if (REQtxtName == "P508")
                //    {
                //        REQtxtName = "P508JS";
                //    }

                //}
                string txtPath = REQtxtName;
                System.Text.Encoding encoding = Encoding.Default;
                string filePath = Public.Apppath + "txt\\REQ\\" + txtPath + ".txt";
                System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.IO.StreamReader sr = new System.IO.StreamReader(fs, encoding);

                //记录每次读取的一行记录
                string strLine = "";
                //记录每行记录中的各字段内容
                string[] aryLine = null;
                string[] tableHead = null;
                //标示列数
                int columnCount = 0;
                //标示是否是读取的第一行
                bool IsFirst = true;
                //逐行读取CSV中的数据
                string WPGTTL = "";

                while ((strLine = sr.ReadLine()) != null)
                {
                    REQclass RC = new REQclass();
                    string[] strLinelist = strLine.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    RC.StrName = strLinelist[0];
                    RC.Strvalue = strLine;
                    strREQ.Add(RC);

                }
                //==================================特殊条件添加

                for(int i=0;i< strREQ.Count();i++)
                {
                    if (strREQ[i].StrName == "WPGTTL")
                    {
                        if (PowerPN == "LA3600-220S87M")
                        {
                            strREQ[i].Strvalue = "WPGTTL" + " " + "0";
                        }
                        else if(power == "3000")
                        {
                            //strREQ[i].Strvalue = "WPGTTL" + " " + "0";
                        }
                        else
                        {
                            strREQ[i].Strvalue = "WPGTTL" + " " + "1";
                        }
                    }
                    //else if (strREQ[i].StrName == "WPDPOS")
                    //{
                    //    if(Is235==true  || power=="1500" || power == "1000")
                    //    {
                    //        strREQ[i].Strvalue = "WPDPOS" + " 1 0 0 1";
                    //    }
                    //    else
                    //    {
                    //        strREQ[i].Strvalue = "WPDPOS" + " 1 1 0 1";

                    //    }
                    //}
                    else
                    {
                        continue;
                    }
                }
               
                //==================================特殊条件添加
                sr.Close();
                fs.Close();
                return strREQ;
            }
            catch (Exception ex)
            {
                 TraceMethodInfo(ex.Message+ex.StackTrace);
                return strREQ;
            }
        }
        public static bool SeekWCON(string PN, string 文件号001, out string strWCON)
        {
            try
            {
                bool resuilt = false;
                DataRow[] DR;
                //string powerletter = PN.Substring(10, 1);
                //if (PowerLetter.ContainsKey(powerletter))
                //{
                //    powerletter = PowerLetter[powerletter].ToString();
                //}
                //string power = PN.Substring(6, 4) + powerletter;
                strWCON = "WCON";
                int N = WCON.Columns.Count;
                string NN = PN.Substring(PN.Length - 2, 2);//检测结尾有没有-N,有就去掉再匹配
                if (NN == "-N") PN = PN.Substring(0, PN.Length - 2);
                if (NN == "-H") PN = PN.Substring(0, PN.Length - 2);
                string[] yunArray = PN.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                string power = yunArray[1];
                int powerindex= PN.IndexOf(power);
                int startIndex = powerindex + power.Length + 1;
                string OFM = PN.Substring(startIndex, PN.Length- startIndex);//检测结尾有没有-N,有就去掉再匹配
                power = power.Substring(2, power.Length - 2);

                DR = WCON.Select("功率型号 = '" + power + "'and  光纤型号= '" + OFM + "' ");

                //if (DR.Length < 0)
                //{
                //    string OFM = PN.Substring(12, 1);
                //    DR = WCON.Select("功率型号 = '" + power + "'and  光纤型号= '" + OFM + "' ");
                //}

                if (DR.Count() == 0) //报错
                {
                    return resuilt;
                }
                //组成WCON字符串
                for (int i = 3; i < N; i++)
                {
                    if (i == 3)
                    {
                        strWCON = strWCON + " " + 文件号001;
                    }
                    else
                    {
                        strWCON = strWCON + " " + Convert.ToString(DR[0][i]);
                    }
                }
                resuilt = true;
                return resuilt;
            }
            catch (Exception ex)
            {
                strWCON = "WCON";
                return false;

            }
        }
        public static bool FindRPV(string REQName, Data0 data0, Data1 data1, out string MPC0, out string RPV,string IP,string power)
        {
            try
            {
                string V12 = "0";
                string V34 = "0";
                string MPC1 = "0", MPC2 = "0";
                int Is235 = 0;
                bool BoolReturn = false;
                //if (REQName.Substring(0, 4) == "P235")
                //{
                //    Is235 = 1;
                //}
                //else
                //{
                //    Is235 = 0;
                //}
                if (mysqlread(data0, data1, REQName,out MPC0, out V12, out V34, out MPC1,out MPC2,IP,out Is235,power))
                {
                    RPV = "RPV" + " " + V12 + " " + V34 + " " + MPC1 + " " + MPC2 + " " + Is235;
                    BoolReturn = true;
                }
                else
                {                
                    RPV = "";
                    BoolReturn = false;                    
                }
                return BoolReturn;
            }
            catch(Exception ex) 
            {
                string V12 = "0";
                string V34 = "0";
                string MPC2 = "0";
                bool Is235 = false;
                MPC0 = ""; RPV = "";
                bool BoolReturn = false;
                 TraceMethodInfo(ex.Message+ex.StackTrace);
                return BoolReturn;
            }         
        }
        public static bool mysqlread(Data0 data0, Data1 data1, string REQName, out string MPC, out string V12, out string V34, out string MPC1, out string MPC2, string IP, out int Is235,string power)
        {           
            
            try
            {
                
                double sumI = 0;
                double MPC调整 = 0;

                List<double> 电流 = new List<double>();
                List<double> 电压 = new List<double>();
                if (data0.power1=="0")
                {
                    MPC = "";
                    MPC1 = "";
                    MPC2 = "";
                    V12 = "";
                    V34 = "";
                    Is235 = 0;
                    string message = "泵源数量:0" ;
                    TraceMethodInfo(message);
                    //DigitalService.CreatLog(IP,message);
                    return false;
                }
                //光光效率数据源
                List<double> Io = new List<double>();
                List<double> Ith = new List<double>();
                List<double> Po = new List<double>();
                //光光效率计算值
                int myDR = 0;

                decimal.TryParse(data0.voltage1, out decimal voltage1);
                data0.voltage1 = voltage1.ToString();
                decimal.TryParse(data0.voltage2, out decimal voltage2);
                data0.voltage2 = voltage2.ToString();
                decimal.TryParse(data0.voltage3, out decimal voltage3);
                data0.voltage3 = voltage3.ToString();
                decimal.TryParse(data0.voltage4, out decimal voltage4);
                data0.voltage4 = voltage4.ToString();

                decimal.TryParse(data0.current1, out decimal current1);
                data0.current1 = current1.ToString();
                decimal.TryParse(data0.current2, out decimal current2);
                data0.current2 = current2.ToString();
                decimal.TryParse(data0.current3, out decimal current3);
                data0.current3 = current3.ToString();
                decimal.TryParse(data0.current4, out decimal current4);
                data0.current4 = current4.ToString();

                decimal.TryParse(data0.power1, out decimal power1);
                data0.power1 = power1.ToString();
                decimal.TryParse(data0.power2, out decimal power2);
                data0.power2 = power2.ToString();
                decimal.TryParse(data0.power3, out decimal power3);
                data0.power3 = power3.ToString();
                decimal.TryParse(data0.power4, out decimal power4);
                data0.power4 = power4.ToString();

                decimal.TryParse(data0.threshold_current1, out decimal threshold_current1);
                data0.threshold_current1 = threshold_current1.ToString();
                decimal.TryParse(data0.threshold_current2, out decimal threshold_current2);
                data0.threshold_current2 = threshold_current2.ToString();
                decimal.TryParse(data0.threshold_current3, out decimal threshold_current3);
                data0.threshold_current3 = threshold_current3.ToString();
                decimal.TryParse(data0.threshold_current4, out decimal threshold_current4);
                data0.threshold_current4 = threshold_current4.ToString();

                //if (data0.power3 != "0" && data0.power4 != "0" && data0.power3 !="" && data0.power4 !="" && data0.power3 != "/" && data0.power4 != "/")
                //{
                //    myDR = 4;
                //}
                //else
                //{
                //    myDR = 2;
                //}
                if (power.Contains("30"))
                {
                    myDR = 4;
                }
                else
                {
                    myDR = 2;
                }

                //myDR = 2;
                for (int i = 0; i < myDR; i++)
                {
                    Io.Add(0); Ith.Add(0); Po.Add(0);
                }
                Public.EP[IP].Io = Io; Public.EP[IP].Ith = Ith; Public.EP[IP].Po = Po;

                for (int i = 0; i < myDR; i++)
                {
                    电流.Add(0); 电压.Add(0);
                }
                if (myDR == 2)
                {
                    double Io_DR = Convert.ToDouble(data0.current1);
                    double Vo_DR = Convert.ToDouble(data0.voltage1);
                    double Po_DR = Convert.ToDouble(data0.power1);
                    //double Ith_DR = Convert.ToDouble(data0.threshold_current1);
                    double Ith_DR = 0;

                    电流[0] = Io_DR; 电压[0] = Vo_DR;
                    Public.EP[IP].Ith[0] = Ith_DR;
                    Public.EP[IP].Io[0] = Io_DR;
                    Public.EP[IP].Po[0] = Po_DR;                 

                    double Io_DR1 = Convert.ToDouble(data0.current2);
                    double Vo_DR1 = Convert.ToDouble(data0.voltage2);
                    double Po_DR1 = Convert.ToDouble(data0.power2);
                    //double Ith_DR1 = Convert.ToDouble(data0.threshold_current2);
                    double Ith_DR1 = 0;

                    电流[1] = Io_DR; 电压[1] = Vo_DR1;
                    Public.EP[IP].Ith[1] = Ith_DR1;
                    Public.EP[IP].Io[1] = Io_DR1;
                    Public.EP[IP].Po[1] = Po_DR1;
                }
                else if (myDR == 4)
                {
                    double Io_DR = Convert.ToDouble(data0.current1);
                    double Vo_DR = Convert.ToDouble(data0.voltage1);
                    double Po_DR = Convert.ToDouble(data0.power1);
                    double Ith_DR = Convert.ToDouble(data0.threshold_current1);

                    电流[0] = Io_DR; 电压[0] = Vo_DR;
                    Public.EP[IP].Ith[0] = Ith_DR;
                    Public.EP[IP].Io[0] = Io_DR;
                    Public.EP[IP].Po[0] = Po_DR;

                    double Io_DR1 = Convert.ToDouble(data0.current2);
                    double Vo_DR1 = Convert.ToDouble(data0.voltage2);
                    double Po_DR1 = Convert.ToDouble(data0.power2);
                    double Ith_DR1 = Convert.ToDouble(data0.threshold_current2);

                    电流[1] = Io_DR; 电压[1] = Vo_DR1;
                    Public.EP[IP].Ith[1] = Ith_DR1;
                    Public.EP[IP].Io[1] = Io_DR1;
                    Public.EP[IP].Po[1] = Po_DR1;

                    double Io_DR2 = Convert.ToDouble(data0.current3);
                    double Vo_DR2 = Convert.ToDouble(data0.voltage3);
                    double Po_DR2 = Convert.ToDouble(data0.power3);
                    double Ith_DR2 = Convert.ToDouble(data0.threshold_current3);

                    电流[2] = Io_DR; 电压[2] = Vo_DR2;
                    Public.EP[IP].Ith[2] = Ith_DR2;
                    Public.EP[IP].Io[2] = Io_DR2;
                    Public.EP[IP].Po[2] = Po_DR2;

                    double Io_DR3 = Convert.ToDouble(data0.current4);
                    double Vo_DR3 = Convert.ToDouble(data0.voltage4);
                    double Po_DR3 = Convert.ToDouble(data0.power4);
                    double Ith_DR3 = Convert.ToDouble(data0.threshold_current4);

                    电流[3] = Io_DR; 电压[3] = Vo_DR3;
                    Public.EP[IP].Ith[3] = Ith_DR3;
                    Public.EP[IP].Io[3] = Io_DR3;
                    Public.EP[IP].Po[3] = Po_DR3;
                }
                else
                {
                    MPC = "";
                    MPC1 = "";
                    MPC2 = "";
                    V12 = "";
                    V34 = "";
                    Is235 = 0;
                    TraceMethodInfo("泵源编号:0");
                    //DigitalService.CreatLog(IP, message);
                    return false;
                }
                
                //============================================================
                double sumIth = 0; double sumIo = 0; double sumPo = 0;
                for (int i = 0; i < Public.EP[IP].Ith.Count; i++)
                {
                    sumIth = sumIth + Public.EP[IP].Ith[i];
                    sumIo = sumIo + Public.EP[IP].Io[i];
                    sumPo = sumPo + Public.EP[IP].Po[i];
                }
                double averageIo = sumIo / Public.EP[IP].Io.Count;
                double averageIth = sumIth / Public.EP[IP].Ith.Count;
                Public.EP[IP].K0 = sumPo / (averageIo - averageIth);
                Public.EP[IP].Y0 = (sumPo * averageIth) / (averageIo - averageIth);
                Public.EP[IP].I3000 = "";
                Public.EP[IP].I2800 = "";
                Public.EP[IP].电流百分比3000 = "";
                Public.EP[IP].电流百分比2800 = "";
                //============================================================
                if (REQName == "P2352000")
                {
                    if (电流.Count() == 2)
                    {
                        Is235 = 1;
                        if (电流[0] > 电流[1])
                        {
                            MPC = (电流[0] + MPC调整).ToString("#0.000");
                            MPC1 = (电流[0]).ToString("#0.000");
                            MPC2 = (电流[1]).ToString("#0.000");
                        }
                        else
                        {
                            MPC = (电流[1] + MPC调整).ToString("#0.000");
                            MPC1 = (电流[1]).ToString("#0.000");
                            MPC2 = (电流[0]).ToString("#0.000");
                        }
                    }
                    else if (电流.Count() == 4)
                    {
                        Is235 = 0;
                        for (int i = 0; i < 电流.Count(); i++)
                        {
                            sumI = sumI + 电流[i];
                        }

                        MPC = ((sumI / 电流.Count()) + MPC调整).ToString("#0.000");
                        MPC1 = ((sumI / 电流.Count())).ToString("#0.000");
                        MPC2 = "0";
                    }
                    else
                    {
                        MPC = "";
                        MPC1 = "";
                        MPC2 = "";
                        TraceMethodInfo("P2352000泵源数量:" + myDR.ToString());
                        string message = "P2352000泵源数量:" + myDR.ToString();
                        //DigitalService.CreatLog(IP, message);
                    }
                    if (电压.Count() == 2)
                    {
                        Is235 = 1;
                        V12 = 电压[0].ToString("#0.0");
                        V34 = 电压[1].ToString("#0.0");
                    }
                    else if (电压.Count() == 4)
                    {
                        Is235 = 0;
                        double DV12 = 电压[0] + 电压[1];
                        double DV34 = 电压[2] + 电压[3];
                        V12 = DV12.ToString("#0.0");
                        V34 = DV34.ToString("#0.0");
                    }
                    else
                    {
                        Is235 = 0;
                        V12 = "";
                        V34 = "";
                        TraceMethodInfo("P2352000泵源数量:" + myDR.ToString());
                        string message = "P2352000泵源数量:" + myDR.ToString();
                        //DigitalService.CreatLog(IP, message);
                    }
                }
                else
                {
                    Is235 = 0;
                    int inum = 0;
                    for (int i = 0; i < 电流.Count(); i++)
                    {
                        sumI = sumI + 电流[i];
                        if (电流[i] != 0)
                        {
                            inum++;
                        }
                    }

                    MPC = ((sumI / inum) + MPC调整).ToString("#0.000");
                    MPC1 = ((sumI / inum)).ToString("#0.000");
                    MPC2 = "0";

                    if (电压.Count() == 2)
                    {
                        Double DV12 = 电压[0] + 电压[1];
                        V12 = DV12.ToString("#0.0");
                        V34 = "0.0";
                    }
                    else if (电压.Count() == 4)
                    {
                        Double DV12 = 电压[0] + 电压[2];
                        Double DV34 = 电压[1] + 电压[3];
                        V12 = DV12.ToString("#0.0");
                        V34 = DV34.ToString("#0.0");
                    }
                    else if (电压.Count() == 6)
                    {
                        Double DV12 = 电压[0] + 电压[1] + 电压[2];
                        Double DV34 = 电压[3] + 电压[4] + 电压[5];
                        V12 = DV12.ToString("#0.0");
                        V34 = DV34.ToString("#0.0");
                    }
                    else if (电压.Count() == 12)
                    {
                        Double DV12 = 电压[0] + 电压[1] + 电压[2] + 电压[3] + 电压[4] + 电压[5];
                        Double DV34 = 电压[6] + 电压[7] + 电压[8] + 电压[9] + 电压[10] + 电压[11];
                        V12 = DV12.ToString("#0.0");
                        V34 = DV34.ToString("#0.0");
                    }
                    else
                    {
                        V12 = "";
                        V34 = "";
                        TraceMethodInfo("非P2352000泵源数量:" + myDR.ToString());
                        string message = "非P2352000泵源数量:" + myDR.ToString();
                        //DigitalService.CreatLog(IP, message);
                    }
                }
                return true;
                //MySqlCmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                TraceMethodInfo(ex.Message + ex.StackTrace);
                V12 = "0"; V34 = "0"; MPC = "0"; MPC1 = "0"; MPC2 = "0"; Is235 = 0;
                return false;
            }
            
        }
        public static bool Readfile(string filePath, out IWorkbook IBook)
        {
            bool flag = false; IBook = null;
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
            openFile.FilterIndex = 2;
            openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            openFile.Multiselect = false;


            string fileType = System.IO.Path.GetExtension(filePath);
            if (string.IsNullOrEmpty(fileType))
            {
                MessageBox.Show("路径位空！");
                return flag;
            }
            FileStream fs = null;
            try
            {
                using (fs = File.OpenRead(filePath))
                {
                    // 2007版本
                    if (filePath.IndexOf(".xlsx") > 0)
                    {
                        IBook = new XSSFWorkbook(fs);
                        flag = true;
                    }
                    // 2003版本
                    else if (filePath.IndexOf(".xls") > 0)
                    {
                        IBook = new HSSFWorkbook(fs);
                        flag = true;
                    }

                    if (IBook == null)
                    {
                        MessageBox.Show("找不到文件！");
                    }
                }
            }
            catch (Exception ex)
            {
                 TraceMethodInfo(ex.Message+ex.StackTrace);
                if (fs != null)
                {
                    fs.Close();
                }
            }
            return flag;
        }
        public static DataTable ReadQueryTable(bool isColumnName, IWorkbook IBook)
        {

            bool jump = false;
            DataTable dataTable = new DataTable();
            DataColumn column = null;
            DataRow dataRow = null;

            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            try
            {

                if (IBook != null)
                {
                    sheet = IBook.GetSheetAt(0);//读取第一个sheet，当然也可以循环读取每个sheet
                                                //sheet = Public.workbook.GetSheet("电机");
                                                //sheet = workbook.GetSheet("shop floor plan");
                    dataTable = new DataTable();
                    if (sheet != null)
                    {
                        int rowCount = sheet.LastRowNum;//总行数
                        if (rowCount > 0)
                        {
                            IRow firstRow = sheet.GetRow(0);//第一行
                            int cellCount = firstRow.LastCellNum;//列数

                            //构建datatable的列
                            if (isColumnName)
                            {
                                startRow = 1;//如果第一行是列名，则从第二行开始读取
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    cell = firstRow.GetCell(i);
                                    if (cell != null)
                                    {
                                        if (cell.StringCellValue != null)
                                        {
                                            column = new DataColumn(cell.StringCellValue);
                                            dataTable.Columns.Add(column);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    column = new DataColumn("column" + (i + 1));
                                    dataTable.Columns.Add(column);
                                }
                            }

                            //填充行
                            for (int i = startRow; i <= rowCount; ++i)
                            {
                                row = sheet.GetRow(i);
                                if (row == null) continue;

                                dataRow = dataTable.NewRow();
                                for (int j = row.FirstCellNum; j < cellCount; j++)
                                {
                                    cell = row.GetCell(j);
                                    if (cell == null)
                                    {
                                        dataRow[j] = "";
                                        //jump = true;
                                    }
                                    else
                                    {
                                        //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                        switch (cell.CellType)
                                        {
                                            case CellType.Blank:
                                                dataRow[j] = "";
                                                break;
                                            case CellType.Numeric:
                                                short format = cell.CellStyle.DataFormat;
                                                //对时间格式（2015.12.5、2015/12/5、2015-12-5等）的处理
                                                if (format == 14 || format == 31 || format == 57 || format == 58)
                                                {
                                                    dataRow[j] = cell.DateCellValue;
                                                }

                                                else
                                                {
                                                    dataRow[j] = cell.NumericCellValue;
                                                }
                                                break;
                                            case CellType.String:
                                                dataRow[j] = cell.StringCellValue;

                                                break;
                                        }
                                        jump = false;
                                    }
                                }
                                if (jump == false) dataTable.Rows.Add(dataRow);
                            }
                        }
                    }
                }

                return dataTable;
            }
            catch (Exception ex)
            {
                 TraceMethodInfo(ex.Message+ex.StackTrace);
                return null;
            }
        }
        public static DateTime ChinaAreaTime(DateTime DT)
        {
            DateTime chinaDT = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DT, "China Standard Time"); //中国标准时间
            return chinaDT;

        }
        public static void 计时起点() //返回起始点数值
        {
            QueryPerformanceFrequency(ref freq);
            QueryPerformanceCounter(ref start_Value);
        }
        public static void 计时终点()//计算与起始点的差值返回毫秒单位的时间差
        {
            QueryPerformanceCounter(ref stop_Value);
            时间差 = (double)(stop_Value - start_Value) / (double)(freq) * 1000;
        }
        //日志信息
        public static void NLOGex(Exception ex)
        {
            //System.Diagnostics.StackTrace SS = new System.Diagnostics.StackTrace(true);
            //System.Reflection.MethodBase MB = SS.GetFrame(1).GetMethod();
            //string[] stringSeparators = new string[] { "line" };
            //string[] yunArray = ex.StackTrace.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
            //string 方法名 = MB.Name;
            //string 类名 = MB.DeclaringType.FullName;
            //string 空间名 = MB.DeclaringType.Namespace;
            //Public.Logger.Error(类名 + "." + 方法名 + yunArray[1] + "行");
            //Public.Logger.Error(ex.Message);
        }
        /// <summary>
        /// 获得调用函数的类名和方法。
        /// </summary>
        /// <returns></returns>
        public static void TraceMethodInfo(string message)
        {
            // 注意：StackTrace的参数1非常重要，表示获得父一级函数调用的相关信息。
            // 如果修改为0，则返回本身的行列信息，即TraceMethodInfo()函数的信息。
            StackFrame st = new System.Diagnostics.StackTrace(1, true).GetFrame(0);
            //string info = string.Format("{0}->{1}_{2}@{3}:{4}",
            //    st.GetFileName(),                       // 文件名
            //    st.GetMethod().DeclaringType.FullName,  // 类全名
            //    st.GetMethod().Name,                    // 方法名
            //    st.GetFileLineNumber(),                 // 所在行号
            //    st.GetFileColumnNumber());              // 所有列号

            string 文件名 = st.GetFileName();
            string 类全名 = st.GetMethod().DeclaringType.FullName;
            string 方法名 = st.GetMethod().Name;
            string 行号 = st.GetFileLineNumber().ToString();
            string 列号 = st.GetFileColumnNumber().ToString();
            //Public.Logger.Info("类：" + 类全名 + "方法：" + 方法名 + "行：" + 行号 + "列：" + 列号);
            //return info;
        }

        //按规则替换字符串
        private static string FomatName(string name)
        {
            var replacements = new Dictionary<char, char>()
            {
                {'/','=' },
                {'-','@' },
                {'$','#' }
            };
            StringBuilder sb = new StringBuilder();
            foreach (char ch in name)
            {
                char replaced;
                if (replacements.TryGetValue(ch, out replaced))
                {
                    sb.Append(replaced);
                }
                else
                {
                    sb.Append(ch);
                }
            }
            return sb.ToString();
        }
        public static bool Seekfirstchar(string type, string str)
        {
            Regex regChina = new Regex("^[^\x00-\xFF]");
            Regex regNum = new Regex("^[0-9]");
            Regex regChar = new Regex("^[a-z]");
            Regex regDChar = new Regex("^[A-Z]");

            bool state;

            switch (type)
            {
                case "数字":
                    if (regNum.IsMatch(str))
                    {
                        state = true;
                    }
                    else
                    {
                        state = false;
                    }
                    break;

                case "中文":
                    if (regChina.IsMatch(str))
                    {
                        state = true;
                    }
                    else
                    {
                        state = false;
                    }
                    break;

                case "小写":
                    if (regChar.IsMatch(str))
                    {
                        state = true;
                    }
                    else
                    {
                        state = false;
                    }
                    break;
                case "大写":
                    if (regDChar.IsMatch(str))
                    {
                        state = true;
                    }
                    else
                    {
                        state = false;
                    }
                    break;
                default:
                    state = false;
                    break;
            }
            return state;
        }
        public static DataTable Distinct(DataTable dt, string[] filedNames)
        {
            DataView dv = dt.DefaultView;
            DataTable DistTable = dv.ToTable(true, filedNames);
            return DistTable;
        }
        public static string ConvertString(string value, int fromBase, int toBase)
        {
            int n = Convert.ToInt32(value, fromBase);
            return Convert.ToString(n, toBase);
        }
        public static void ErrorCatch(Exception ex)
        {
            string str = ex.StackTrace; string filepath = @"C:\DebugRecord.txt";
            //Console.WriteLine($"{DateTime.Now}+{str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1)}+{ex.Source}+{ex.Message}");
            using (FileStream stream = new FileStream(filepath, FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now}+{str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1)}+{ex.Source}+{ex.Message}");
            }
        }
        public static double RD(float value)
        {
            double f1 = Convert.ToDouble(Math.Round(Convert.ToDecimal(value), 2, MidpointRounding.AwayFromZero).ToString());
            return f1;
        }
        public static double FinalValue(double F1, double ValueMax, double ValueMin, double SignalMax, double SignalMin)
        {
            double faResult;
            faResult = ((ValueMax - ValueMin) / (SignalMax - SignalMin)) * (F1 - SignalMin) + ValueMin;
            return faResult;
        }

        public static void SendMail(object obj)
        {

            try
            {
                EquipmentList Eql = obj as EquipmentList;
               
                var emailAcount = ""; var emailPassword = ""; var STRreciver = ""; var STRcontent = "";
                STRcontent = Eql.Local_EquipmentNumber + Eql.Local_EquipmentName2 + "采集中断";
                switch (Eql.Local_EquipmentArea)
                {
                    case "MACHINING":
                        STRreciver = "U270280@danfoss.com";
                        break;
                    case "NELICO":
                        STRreciver = "LuoJie@danfoss.com";
                        break;
                    case "PERFORMER":
                        STRreciver = "renfei@danfoss.com";
                        break;
                    case "SHELL":
                        STRreciver = "ruibo.fang@danfoss.com";
                        break;
                    case "BYD":
                        STRreciver = "U368663@danfoss.com";
                        break;
                    case "PUBLIC":
                        STRreciver = "ping-m.li@danfoss.com";
                        break;

                    default:
                        Console.WriteLine("Default case");
                        break;

                }
                var reciver = STRreciver;
                var content = STRcontent;
                MailMessage message = new MailMessage();
                //设置发件人,发件人需要与设置的邮件发送服务器的邮箱一致
                MailAddress fromAddr = new MailAddress("CNCC_EMS@danfoss.com", "CNCC能耗数据采集监控系统");
                message.From = fromAddr;
                //设置收件人,可添加多个,添加方法与下面的一样
                message.To.Add(reciver);
                //设置抄送人
                message.CC.Add("kuiyuan.dou@danfoss.com");
                //message.CC.Add("sunhailiang@danfoss.com");
                //message.CC.Add("yjhwzf@danfoss.com");
                //设置邮件标题
                message.Subject = "系统报警";
                //设置邮件内容
                message.Body = content;
                //设置邮件发送服务器,服务器根据你使用的邮箱而不同,可以到相应的 邮箱管理后台查看,下面是QQ的
                SmtpClient client = new SmtpClient("smtp.danfoss.net", 25);
                //设置发送人的邮箱账号和密码
                client.Credentials = new NetworkCredential(emailAcount, emailPassword);
                //启用ssl,也就是安全发送
                client.EnableSsl = true;
                //发送邮件
                client.Send(message);
          
                //MessageBox.Show("邮件发送合格");//发送合格则提示返回当前页面；
            }
            catch (Exception ex)
            {
                //MessageBox.Show("邮件发送不合格");//打印错误
            }

        }

        public string GetLocalIp()
        {
            ///获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }
    }
}
